<template>
  <div class="components-prod-add-or-update">
    <el-dialog
      v-model="visible"
      :title="
        !dataForm.distributionProdId
          ? $t('marketing.newDisProducts')
          : $t('marketing.modifyDisnProducts')
      "
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        label-width="125px"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-form-item :label="$t('groups.relatedProducts')">
          <div v-if="prodData[0] != null">
            <el-card
              :body-style="{ padding: '0px' }"
              style="height: 160px; width: 120px"
            >
              <ImgShow
                height="104"
                :src="prodData[0].pic"
              />
              <div class="card-prod-info-btn">
                <div class="prod-name">
                  {{ prodData[0].prodName }}
                </div>
                <div class="del-btn">
                  <span @click="deleteRelation">{{ $t('text.delBtn') }}</span>
                </div>
              </div>
            </el-card>
          </div>
          <div
            v-if="prodData[0] == null"
            class="default-btn"
            @click="onAddProd"
          >
            {{ $t('product.select') }}
          </div>
        </el-form-item>
        <div v-if="dataForm.defaultReward === 0">
          <el-form-item
            :label="$t('marketing.rewardRatio')"
            prop="awardType"
          >
            <el-radio-group v-model="dataForm.awardProportion">
              <el-radio :label="0">
                {{ $t('marketing.proporteward') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('marketing.rewardByFixedValue') }}
                <el-tooltip
                  class="item"
                  effect="light"
                  placement="top"
                >
                  <template #content>
                    <div>{{ $t('marketing.tips') }}</div>
                  </template>
                  <span>
                    <el-icon><QuestionFilled /></el-icon>
                  </span>
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            :label="$t('marketing.inviterReward')"
            prop="awardType"
          >
            <el-radio-group v-model="dataForm.parentAwardSet">
              <el-radio :label="0">
                {{ $t('station.close') }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('groups.turnOn') }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            :label="
              dataForm.awardNumberSet === 1
                ? $t('marketing.rewardSettings')
                : $t('marketing.defaultReward')
            "
            prop="awardType"
          >
            <div v-if="dataForm.awardNumberSet === 0">
              <el-input
                v-model="dataForm.awardNumbers"
                :precision="2"
                :min="1"
                style="width: 200px"
                type="number"
                @blur="numberFormat('awardNumbers')"
              >
                <template #append>
                  <span v-if="dataForm.awardProportion === 1">{{ $t('admin.dollar') }}</span>
                  <span v-else>%</span>
                </template>
              </el-input>

              <span v-if="dataForm.parentAwardSet === 1">&nbsp; {{ $t('marketing.inviterReward') }}:</span>
              <el-input
                v-if="dataForm.parentAwardSet === 1"
                v-model="dataForm.parentAwardNumbers"
                :precision="2"
                :min="1"
                style="width: 200px"
                type="number"
                @blur="numberFormat('parentAwardNumbers')"
              >
                <template #append>
                  <span v-if="dataForm.awardProportion === 1">{{ $t('admin.dollar') }}</span>
                  <span v-else>%</span>
                </template>
              </el-input>
            </div>
            <div v-if="dataForm.awardNumberSet === 1">
              <el-table
                :data="levelData"
                max-height="250"
              >
                <el-table-column
                  prop="name"
                  :label="$t('marketing.name')"
                  fit
                />

                <el-table-column
                  :label="$t('marketing.rewardAmount')"
                  width="300"
                >
                  <template #default="scope">
                    <el-input
                      v-model="levelData[scope.$index].awardNumber"
                      :placeholder="$t('product.content')"
                      type="number"
                    >
                      <template #append>
                        <span v-if="dataForm.awardProportion === 1">{{ $t('admin.dollar') }}</span>
                        <span v-else>%</span>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>

                <el-table-column
                  v-if="dataForm.parentAwardSet === 1"
                  :label="$t('marketing.inviterReward')"
                  width="300"
                >
                  <template #default="scope">
                    <el-input
                      v-model="levelData[scope.$index].parentAwardNumber"
                      :placeholder="$t('product.content')"
                      type="number"
                    >
                      <template #append>
                        <span v-if="dataForm.awardProportion === 1">{{ $t('admin.dollar') }}</span>
                        <span v-else>%</span>
                      </template>
                    </el-input>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </div>

        <el-form-item
          :label="$t('product.status') + ':'"
          prop="state"
        >
          <el-radio-group v-model="dataForm.state">
            <el-radio :label="1">
              {{ $t('publics.UpperShelf') }}
            </el-radio>
            <el-radio :label="0">
              {{ $t('publics.LowerShelf') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t('crud.filter.cancelBtn') }}
          </div>
          <div
            class="default-btn primary-btn"
            type="primary"
            @click="onSubmit()"
          >
            {{ $t('crud.filter.submitBtn') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 弹窗, 新增 / 修改 -->
    <ViewOrSelectProd
      v-if="addProdVisible"
      ref="addProdRef"
      :is-distribution="true"
      @refresh-discount-prods="onSelectDiscountProds"
    />
  </div>
</template>

<script setup>
import ViewOrSelectProd from '../../../components/view-or-select-prod.vue'
import { ref, nextTick, toRaw } from 'vue'
import $t from '@/utils/$t.js'
import http from '@/utils/http.js'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])
const dataFormRef = ref(null)

const dataForm = ref({
  prodId: 0,
  distributionAmount: 0,
  awardId: 0,
  state: 1,
  defaultReward: 1,
  awardProportion: 0,
  awardNumberSet: 0,
  awardNumbers: '',
  parentAwardNumbers: '',
  parentAwardSet: 0
})
const isSubmit = ref(false)
const levelData = ref([])
const prodData = ref([])
const addProdVisible = ref(false)
const visible = ref(false)

const init = data => {
  visible.value = true
  isSubmit.value = false
  if (data) {
    dataForm.value = Object.assign(dataForm.value, data)
    prodData.value[0] = dataForm.value.product
  } else {
    nextTick(() => {
      dataFormRef.value.resetFields()
      dataForm.value.defaultReward = 0
      dataForm.value.awardProportion = 0
      dataForm.value.awardNumberSet = 0
      dataForm.value.parentAwardSet = 0
      dataForm.value.awardNumbers = 1
      dataForm.value.parentAwardNumbers = 1
      dataForm.value.state = 1
      levelData.value = []
      prodData.value = []
      dataForm.value.distributionProdId = 0
    })
  }
}
const checkAwardNumbers = number => {
  if (!number) {
    ElMessage.error($t('marketing.valueSetBeEmpty'))
    return true
  }
  const regex = /^((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/
  if (!regex.test(number) || number > 100 || number === '0') {
    ElMessage.error($t('marketing.valueSetting'))
    return true
  }
  if (dataForm.value.parentAwardSet && !dataForm.value.awardProportion) {
    if (
      parseFloat(dataForm.value.parentAwardNumbers) + parseFloat(dataForm.value.awardNumbers) >=
      100
    ) {
      ElMessage.error(
        $t('marketing.rewardAmount') +
          '+' +
          $t('marketing.inviterReward') +
          $t('marketing.totalAwardOverTips')
      )
      return true
    }
    if (parseFloat(dataForm.value.awardNumbers) > 100) {
      ElMessage.error($t('marketing.rewardRatio') + $t('marketing.totalAwardOverTips'))
      return true
    }
  }
}
const numberFormat = attr => {
  let val = parseFloat(dataForm.value[attr] || 0).toFixed(2)
  if (val <= 0) {
    val = 1
  }
  dataForm.value[attr] = val
}
// 删除关联商品数据
const deleteRelation = () => {
  dataForm.value.prodId = null
  prodData.value = []
}
// 打开选择商品
const addProdRef = ref(null)
const onAddProd = () => {
  addProdVisible.value = true
  nextTick(() => {
    addProdRef.value.init(0, prodData.value)
  })
}
// 商品选择回调
const onSelectDiscountProds = prods => {
  if (prods?.length) {
    nextTick(() => {
      http({
        url: http.adornUrl('/distribution/distributionProd/count'),
        method: 'get',
        params: http.adornParams({
          prodId: prods[0].prodId
        })
      }).then(({ data }) => {
        if (data === 0) {
          dataForm.value.prodId = prods[0].prodId
          prodData.value[0] = prods[0]
        } else {
          ElMessage({
            message: $t('marketing.theProduList'),
            type: 'warning'
          })
        }
      })
    })
  }
}
const checkAwardNumberSet = () => {
  if (dataForm.value.awardNumberSet === 0) {
    if (
      checkAwardNumbers(dataForm.value.awardNumbers) ||
      (dataForm.value.parentAwardSet === 1 && checkAwardNumbers(dataForm.value.parentAwardNumbers))
    ) {
      return true
    }
  }
  if (dataForm.value.awardNumberSet === 1) {
    for (let i = 0; i < levelData.value.length; i++) {
      const level = levelData.value[i]
      if (
        checkAwardNumbers(level.awardNumber) ||
        (dataForm.value.parentAwardSet === 1 && checkAwardNumbers(level.parentAwardNumber))
      ) {
        return true
      }
    }
  }
  return false
}
// 表单提交
const onSubmit = () => {
  if (dataForm.value.defaultReward === 0 && checkAwardNumberSet()) {
    return
  }
  if (prodData.value[0] == null) {
    ElMessage.error($t('marketing.pleaseSelectAProduct'))
    return
  }
  dataFormRef.value.validate(valid => {
    if (valid) {
      if (dataForm.value.awardNumberSet === 1) {
        // 创建json存入奖励表
        const awardNumberjson = []
        const parentAwardNumberjson = []
        levelData.value.forEach(item => {
          awardNumberjson.push(Number.parseFloat(item.awardNumber).toFixed(2))
          parentAwardNumberjson.push(Number.parseFloat(item.parentAwardNumber).toFixed(2))
        })
        dataForm.value.awardNumbers = JSON.stringify(awardNumberjson)
        dataForm.value.parentAwardNumbers = JSON.stringify(parentAwardNumberjson)
      }
      const param = toRaw(dataForm.value)
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/distribution/distributionProd'),
        method: param.distributionProdId ? 'put' : 'post',
        data: http.adornData(param)
      })
        .then(() => {
          ElMessage({
            message: $t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList')
            }
          })
        })
        .catch(() => {
          isSubmit.value = false
        })
    }
  })
}

// 导出子组件方法
defineExpose({
  init
})
</script>
